Set
A Set is an object available as a data structure.
It has similarities and differences to
MapandObject.MapresembleSetthe most.
Set stores unique values - which can be virtually anything.
info
Compared to mathematical sets, a Set in Hedgehog Script must have unique values with no duplication.
Here is an example of using Set:
One can iterate through a Set in insertion order just like a Map.
The way to add new elements to a Set is using add().
Any implementation of a Set is required to have, on average, sub-linear access times.
info
Just like maps, internally they can be like a hash table with \(\Omega(1)\) lookup time.
Then a search at \(\Omega(\log(N))\) time, and anything else (as long as its better than) with less than \(\Omega(N)\) time.
Set Methods
Here are some vital methods within Set:
Set.has(value)checks if a value is in thatSetobjectOne can create a
Setusing the constructorSet()An example instance property is:
Set.size- (returns number of elements inSet)Set.add()- Inserts a new element with a specified value in to aSetobject, if there isn't one with the same value alreadySet.clear()- Remove all elements from theSetobjectSet.values(),Set.keys()andSet.entries()- returns an iterator that contains: values, keys and entries, respectivelySet.forEach()- Iterates through the values. Similar toArray.forEach()orMap.forEach()
Some examples of using the Set object:
tip
That was a long example! One thing to note is the last function:
- it uses the mentioned method
Set.forEach(),JSON, conditional ternary operator?and an arrow function!
If one is confused this is how it works:
In insertion order,
set1is iterated over and runs the function which takes invalueas the argumentThen it checks if
ais anobject: if so, parse it. Otherwise, keep it the same.Then
printthe value - stringified, soobjectscan be shown!
info
There are quite a lot of elementary functions one can write and use.
More information can be found here: Sets - MDN.
Lastly, a practical function of Set is to decompose String:
- Note that entries are stored as [value, value]
tip
A really good use of Sets is their ability to remove duplicate elements in Arrays:
Just transform the Array to a Set and then the Set back into an Array.